package study.zhangbo.lock.distributed.redis;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * 看门狗线程
 * Created by zhangbo on 2020/10/29.
 */
@Slf4j
public class RedisLockDog implements Runnable {


    private String lockName;

    private AtomicBoolean life;

    private RedisLockUtils redisLockUtils;

    public RedisLockDog(String lockName, AtomicBoolean life, RedisLockUtils redisLockUtils) {
        this.lockName = lockName;
        this.life = life;
        this.redisLockUtils = redisLockUtils;
    }

    @Override
    public void run() {
        log.debug("看门狗开始运行");
        long current = System.currentTimeMillis();
        while (life.get()) {
            if (current + 5 * 1000 < System.currentTimeMillis()) {
                boolean hasKey = redisLockUtils.hasKey(lockName);
                if (hasKey) {
                    redisLockUtils.addKeyTime(lockName, 10, TimeUnit.SECONDS);
                } else {
                    throw new RuntimeException("key丢失，看门狗非正常退出");
                }
                current = System.currentTimeMillis();
            }

        }
        log.debug("看门狗正常退出");
    }

}
